<template>
  <div class="profile-edit-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button @click="$router.back()" :icon="ArrowLeft" text>
        返回个人中心
      </el-button>
      <h1>编辑个人资料</h1>
      <p>更新您的个人信息和头像</p>
    </div>

    <!-- 个人信息编辑卡片 -->
    <el-card class="edit-card">
      <template #header>
        <div class="card-header">
          <h3>基本信息</h3>
          <el-tag type="info" size="small">
            <el-icon><User /></el-icon>
            {{ getRoleText(currentUser?.userRole) }}
          </el-tag>
        </div>
      </template>

      <div class="edit-content">
        <!-- 加载状态 -->
        <div v-if="dataLoading" class="loading-container">
          <el-skeleton :rows="6" animated />
        </div>
        
        <!-- 表单内容 -->
        <el-form
          v-else
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="120px"
          class="edit-form"
          label-position="top"
        >
          <!-- 头像上传区域 -->
          <div class="avatar-section">
            <div class="avatar-container">
              <div class="avatar-display">
                <el-avatar
                  :size="100"
                  :src="avatarPreview || getFileUrl(currentUser?.userAvatar || '')"
                  class="user-avatar"
                >
                  {{ currentUser?.userName?.charAt(0) || 'U' }}
                </el-avatar>
                <div class="avatar-overlay" v-if="!avatarUploading">
                  <el-icon><Camera /></el-icon>
                </div>
                <div class="avatar-loading" v-if="avatarUploading">
                  <el-icon class="is-loading"><Loading /></el-icon>
                </div>
              </div>
              <div class="avatar-controls">
                <el-upload
                  ref="uploadRef"
                  :before-upload="beforeAvatarUpload"
                  :http-request="handleAvatarUpload"
                  :show-file-list="false"
                  accept="image/*"
                  class="avatar-uploader"
                >
                  <el-button type="primary" :loading="avatarUploading" size="small">
                    {{ avatarUploading ? '上传中...' : '更换头像' }}
                  </el-button>
                </el-upload>
                <p class="upload-tips">支持 JPG、PNG 格式，建议尺寸 200x200，不超过 2MB</p>
              </div>
            </div>
          </div>

          <div class="form-grid">
            <!-- 用户昵称 -->
            <el-form-item label="昵称" prop="userName" class="form-item-full">
              <el-input
                v-model="basicForm.userName"
                placeholder="请输入您的昵称"
                maxlength="20"
                show-word-limit
                clearable
                size="large"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <!-- 用户简介 -->
            <el-form-item label="个人简介" prop="userProfile" class="form-item-full">
              <el-input
                v-model="basicForm.userProfile"
                type="textarea"
                placeholder="介绍一下自己吧..."
                maxlength="200"
                show-word-limit
                :rows="4"
                resize="none"
              />
            </el-form-item>
          </div>

          <!-- 账户信息展示 -->
          <div class="account-info">
            <h4>账户信息</h4>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">用户名</span>
                <span class="info-value">{{ currentUser?.userAccount || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">注册时间</span>
                <span class="info-value">{{ formatDate(currentUser?.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">最后更新</span>
                <span class="info-value">{{ formatDate(currentUser?.updateTime) }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button
              type="primary"
              size="large"
              :loading="basicLoading"
              @click="handleBasicSave"
            >
              <el-icon><Check /></el-icon>
              保存修改
            </el-button>
            <el-button
              size="large"
              @click="handleBasicReset"
            >
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
            <el-button
              type="warning"
              size="large"
              @click="changePassword"
            >
              <el-icon><Lock /></el-icon>
              修改密码
            </el-button>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      :before-close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
            clearable
            size="large"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
            clearable
            size="large"
          >
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
            clearable
            size="large"
          >
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlePasswordDialogClose" size="large">取消</el-button>
          <el-button type="primary" :loading="passwordLoading" @click="handlePasswordSubmit" size="large">
            确定修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRequestOptions } from 'element-plus'
import { 
  ArrowLeft, 
  Camera, 
  User, 
  Loading, 
  Check, 
  RefreshLeft, 
  Lock, 
  Key 
} from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { UserControllerService } from '../services/UserControllerService'
import type { UserUpdateMyRequest } from '../models/UserUpdateMyRequest'
import type { UserUpdatePasswordRequest } from '../models/UserUpdatePasswordRequest'
import { ImageUtils } from '../utils/imageUtils'
import { uploadAvatar, getFileUrl } from '../utils/uploadUtils'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const basicFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const uploadRef = ref()

// 加载状态
const basicLoading = ref(false)
const avatarUploading = ref(false)
const dataLoading = ref(true) // 数据加载状态
const passwordLoading = ref(false)

// 头像预览
const avatarPreview = ref('')

// 表单数据
const basicForm = reactive({
  userName: '',
  userProfile: ''
})

// 修改密码相关
const passwordDialogVisible = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 当前用户信息，直接使用store中的ref
const currentUser = userStore.currentUser

// 表单验证规则
const basicRules: FormRules = {
  userName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 20, message: '昵称长度为 1-20 个字符', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为 8 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化基本信息表单
const initBasicForm = async () => {
  console.log('开始初始化表单数据...')
  dataLoading.value = true
  
  try {
    // 获取最新的用户数据
    const userData = await userStore.getCurrentUser()
    
    if (userData) {
      console.log('用户数据获取成功，初始化表单:', userData.userName)
      basicForm.userName = userData.userName || ''
      basicForm.userProfile = userData.userProfile || ''
      console.log('表单初始化完成:', { 
        userName: basicForm.userName, 
        userProfile: basicForm.userProfile 
      })
    } else {
      console.error('无法获取用户数据，可能未登录')
      ElMessage.error('获取用户信息失败，请重新登录')
    }
  } catch (error) {
    console.error('表单初始化失败:', error)
    ElMessage.error('初始化失败')
  } finally {
    dataLoading.value = false
  }
}

// 获取角色文本
const getRoleText = (role?: string) => {
  switch (role) {
    case 'admin':
      return '管理员'
    case 'user':
      return '普通用户'
    default:
      return '未知角色'
  }
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 头像上传前检查
const beforeAvatarUpload = async (file: File) => {
  const validation = ImageUtils.validateImageFile(file, 2)
  
  if (!validation.valid) {
    ElMessage.error(validation.message!)
    return false
  }

  // 预览图片
  try {
    avatarPreview.value = await ImageUtils.createPreviewUrl(file)
  } catch (error) {
    console.error('创建预览失败:', error)
  }

  return true
}

// 当前头像URL（仅用于显示，保存时会用到）
const currentAvatarUrl = ref('')

// 处理头像上传
const handleAvatarUpload = async (options: UploadRequestOptions) => {
  try {
    avatarUploading.value = true
    
    // 使用 uploadAvatar 工具函数上传头像
    const response = await uploadAvatar(options.file as File)
    
    if (response.code === 0 && response.data) {
      // 上传成功，提取URL路径
      const avatarUrl = response.data.url
      
      if (avatarUrl) {
        // 保存相对路径URL用于后续保存
        currentAvatarUrl.value = avatarUrl
        // 使用 getFileUrl 获取完整URL用于预览
        avatarPreview.value = getFileUrl(avatarUrl)
        ElMessage.success('头像上传成功，请点击"保存修改"保存更改')
      } else {
        throw new Error('无法从响应中获取文件URL')
      }
    } else {
      throw new Error(response.message || '上传失败')
    }
  } catch (error: any) {
    console.error('头像上传失败:', error)
    ElMessage.error('上传失败: ' + (error.message || '未知错误'))
    avatarPreview.value = ''
    currentAvatarUrl.value = ''
  } finally {
    avatarUploading.value = false
  }
}

// 保存基本信息
const handleBasicSave = async () => {
  if (!basicFormRef.value) return

  try {
    const valid = await basicFormRef.value.validate()
    if (!valid) return

    await ElMessageBox.confirm(
      '确定要保存这些修改吗？',
      '确认保存',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    basicLoading.value = true

    // 确定要保存的头像URL（优先使用新上传的，否则使用当前的）
    const avatarToSave = currentAvatarUrl.value || currentUser?.userAvatar

    const updateRequest: UserUpdateMyRequest = {
      userName: basicForm.userName,
      userProfile: basicForm.userProfile || undefined,
      userAvatar: avatarToSave
    }

    const response = await UserControllerService.updateMyUser(updateRequest)
    
    if (response.code === 0) {
      // 强制刷新用户信息，获取最新数据
      await userStore.refreshCurrentUser()
      // 重置上传状态
      currentAvatarUrl.value = ''
      avatarPreview.value = ''
      ElMessage.success('保存成功')
    } else {
      throw new Error(response.message || '保存失败')
    }
  } catch (error: any) {
    if (error === 'cancel') return
    console.error('保存失败:', error)
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    basicLoading.value = false
  }
}

// 重置基本信息表单
const handleBasicReset = () => {
  initBasicForm()
  avatarPreview.value = ''
  currentAvatarUrl.value = ''
  basicFormRef.value?.clearValidate()
}

// 修改密码相关方法
const changePassword = () => {
  passwordDialogVisible.value = true
}

const handlePasswordDialogClose = () => {
  passwordDialogVisible.value = false
  resetPasswordForm()
}

const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.clearValidate()
}

const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value) return

  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return

    await ElMessageBox.confirm(
      '确定要修改密码吗？修改后需要重新登录。',
      '确认修改',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    passwordLoading.value = true

    const updateRequest: UserUpdatePasswordRequest = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    }

    const response = await UserControllerService.updatePassword(updateRequest)
    
    if (response.code === 0) {
      ElMessage.success('密码修改成功，请重新登录')
      passwordDialogVisible.value = false
      resetPasswordForm()
      // 清除登录状态，跳转到登录页
      await userStore.logout()
      router.push('/login')
    } else {
      throw new Error(response.message || '密码修改失败')
    }
  } catch (error: any) {
    if (error === 'cancel') return
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败: ' + (error.message || '未知错误'))
  } finally {
    passwordLoading.value = false
  }
}

// 监听用户信息变化，自动更新表单
watch(
  () => currentUser,
  (newUser, oldUser) => {
    console.log('User changed in watcher:', { newUser, oldUser })
    if (newUser) {
      nextTick(() => {
        initBasicForm()
      })
    }
  },
  { immediate: true, deep: true }
)

// 组件挂载时初始化数据
onMounted(async () => {
  await initBasicForm()
})
</script>

<style scoped>
.profile-edit-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面头部 */
.page-header {
  text-align: center;
  margin-bottom: 8px;
}

.page-header h1 {
  margin: 16px 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 16px;
}

/* 编辑卡片 */
.edit-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.edit-content {
  padding: 32px;
}

.loading-container {
  padding: 60px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 表单样式 */
.edit-form {
  max-width: 100%;
}

/* 头像区域 */
.avatar-section {
  margin-bottom: 40px;
  padding: 32px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  text-align: center;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.avatar-display {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.user-avatar {
  border: 4px solid #fff;
  font-size: 36px;
  font-weight: bold;
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 12px 32px rgba(64, 158, 255, 0.4);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  font-size: 24px;
}

.avatar-display:hover .avatar-overlay {
  opacity: 1;
}

.avatar-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  font-size: 24px;
}

.avatar-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.upload-tips {
  color: #909399;
  font-size: 13px;
  margin: 0;
  line-height: 1.4;
}

/* 表单网格 */
.form-grid {
  display: grid;
  gap: 24px;
  margin-bottom: 32px;
}

.form-item-full {
  grid-column: 1 / -1;
}

/* 账户信息区域 */
.account-info {
  margin: 32px 0;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.account-info h4 {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.info-value {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

/* 操作按钮 */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 40px;
  padding-top: 32px;
  border-top: 1px solid #e4e7ed;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-edit-container {
    padding: 16px;
    max-width: 100%;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .edit-content {
    padding: 24px 20px;
  }

  .avatar-section {
    padding: 24px 20px;
    margin-bottom: 32px;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .form-actions .el-button {
    width: 100%;
  }

  .info-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .profile-edit-container {
    padding: 12px;
  }

  .page-header h1 {
    font-size: 22px;
  }

  .edit-content {
    padding: 20px 16px;
  }

  .avatar-section {
    padding: 20px 16px;
  }

  .user-avatar {
    font-size: 32px;
  }

  .card-header h3 {
    font-size: 18px;
  }
}

/* 表单项样式优化 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
}
</style>